const MYSQL = require("../mysql");

/**
 * 列表数据
 * @param {string} sqlName 数据表
 */
async function List(sqlName, params = {}) {
  try {
    let {
      where = null,
      query = null,
      paging,
      page = 1,
      limit = 10,
      format = null,
    } = params;
    let query_result = null;
    let paging_query = "";
    let total = null;
    let total_query = null;
    let total_result = null;
    if (query) {
      query = query;
    } else {
      query = `SELECT * FROM ${sqlName} `;
      total_query = `SELECT Count(*) AS total FROM ${sqlName} `;
    }
    if (where) {
      if (typeof where == "object") {
        let whereText = "WHERE ?";
        query += whereText;
        total_query += whereText;
      } else {
        let whereText = `WHERE ${where}`;
        query += whereText;
        total_query += whereText;

        console.log("whereText", whereText);
      }
    }
    if (paging) {
      limit = limit < 1 ? (limit = 1) : limit;
      page = page < 1 ? (page = 1) : page;
      paging_query += ` LIMIT ${(page - 1) * limit + "," + page * limit} `;
    }
    query_result = await MYSQL.promise().query(
      `${query} ${paging_query}`,
      where
    );
    if (paging) {
      total_result = await MYSQL.promise().query(`${total_query}`, where);
      total = total_result[0][0].total;
    }
    let list = query_result[0];
    if (format && typeof format == "function") {
      list = format(list);
    }
    let code = 0,
      msg = "获取成功";
    if (paging) {
      return {
        code,
        msg,
        data: {
          page,
          limit,
          total,
          list: list,
        },
      };
    } else {
      return {
        code,
        msg,
        data: list,
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 更新数据
 * @param {string} sqlName 数据表
 * @param {object} params 配置对象
 * @param {object | Array} params.data 添加的数据对象
 * @param {string} [params.query] 查询语句
 * @param {object | string | boolean} [params.exist] 查询是否存在的查询条件条件
 */
async function Update(sqlName, params) {
  try {
    let { where = {}, update } = params;
    let update_query = `        
        UPDATE ${sqlName}
        SET 
    `;
    if (update) {
      if (typeof update == "object") {
        let whereText = "?";
        update_query += whereText;
      }
    }
    if (where) {
      let whereText = ` WHERE ${where}`;
      update_query += whereText;
    }
    // 更新数据对象去除无效数据
    for (let key of Object.keys(update)) {
      let value = update[key];
      if (value === undefined) {
        delete update[key];
      } else if (value === "") {
        update[key] = null;
      }
    }
    // 处理后的更新数据对象
    console.log("new update", update);
    let Mysql_result = await MYSQL.promise().query(update_query, update);
    let Update_result = Mysql_result[0];
    let { affectedRows } = Update_result;
    if (affectedRows) {
      let code = 0,
        msg = "更新成功";
      return {
        code,
        msg,
      };
    } else {
      let code = 500,
        msg = "更新失败";
      throw {
        code,
        msg,
      };
    }
  } catch (error) {
    console.log("更新失败");
    console.log(error);
    throw { code: 500, msg: "更新失败" };
  }
}
async function Info(sqlName, params) {
  try {
    let { where, query } = params;
  } catch (error) {}
}
/**
 * 添加数据
 * @param {string} sqlName 数据表
 * @param {object} params 配置对象
 * @param {object | Array} params.data 添加的数据对象
 * @param {string} [params.query] 查询语句
 * @param {object | string | boolean} [params.exist] 查询是否存在的查询条件条件
 */
async function Add(sqlName, params = {}) {
  try {
    let { data, query, exist } = params;

    if (exist) {
      let exist_query = `SELECT * FROM ${sqlName} `;
      let existWhere = null;
      let type = typeof exist;
      if (type == "string") {
        exist_query += `where ${exist}`;
      }
      if (type == "object") {
        exist_query += `where ?`;
        existWhere = exist;
      }
      let mysql_result = await MYSQL.promise().query(exist_query, existWhere);
      let exist_result = mysql_result[0];

      if (exist_result.length) {
        throw { code: 500, msg: "添加失败,记录已存在" };
      }
    }
    if (query) {
      query = query;
    } else {
      query = `INSERT INTO ${sqlName} SET `;
    }
    if (data) {
      if (Array.isArray(data)) {
        query += `?`;
      } else if (typeof data == "object") {
        query += `?`;
      } else {
        query += data;
      }
    }

    console.log("添加语句", query);
    console.log("添加数据", data);

    //    // 将本次生成的token存入数据库中
    let mysql_result = await MYSQL.promise().query(query, data);
    let add_result = mysql_result[0];
    let { affectedRows } = add_result;
    if (affectedRows) {
      return {
        code: 0,
        msg: "添加成功",
        affectedRows,
      };
    } else {
      throw {
        code: 500,
        msg: "添加失败，未知错误",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 删除数据
 * @param {string} sqlName 数据表
 * @param {Object} [where={}] 匹配条件，不填写则删除全部
 */
async function Delete(sqlName, where = {}) {
  try {
    let delete_query = `DELETE FROM ${sqlName} `;
    if (where) {
      if (typeof where == "object") {
        let whereText = "WHERE ?";
        delete_query += whereText;
      } else {
        let whereText = `WHERE ${where}`;
        delete_query += whereText;
      }
    }
    let Mysql_result = await MYSQL.promise().query(delete_query, where);
    let Delete_result = Mysql_result[0];
    let { affectedRows } = Delete_result;
    if (affectedRows) {
      let code = 0,
        msg = "删除成功";
      return {
        code,
        msg,
      };
    } else {
      let code = 500,
        msg = "失败失败,记录不存在";
      throw {
        code,
        msg,
      };
    }
  } catch (error) {
    throw error;
  }
}

module.exports = {
  Add,
  List,
  Update,
  Info,
  Delete,
};
